

#ifndef _DRV_PWM_H_
#define _DRV_PWM_H_
#include "driver/driver_common.h"
#include <stdbool.h>
#include <stdint.h>
/*
几点说明：
1，通过drv_pwm_duty_set(uint8_t ch, uint16_t duty)函数调节PWM脉宽的时候，
   duty的值为0-MAX_DUTY_VALUE，PWM的占空比为duty/MAX_DUTY_VALUE。
   综合考虑（一些timer为16位），MAX_DUTY_VALUE值设置为10000。
2，frq_to_period_val(freq)宏定义需要根据timer的频率调整，当timer频率为10K时，其定义为：
  (uint32_t)(10000u / freq - 1)
 */
#define MAX_DUTY_VALUE 10000u
// 当frq<153hz时，16定时器发生溢出

#define frq_to_period_val(freq_pwm, freq_timer) (uint32_t)((freq_timer)/(freq_pwm) - 1)

/*PWM channel mask*/
#define T_CH_0 (1ul << 0)
#define T_CH_1 (1ul << 1)
#define T_CH_2 (1ul << 2)
#define T_CH_3 (1ul << 3)

typedef struct {
  /* The module index associated with the object*/
  SYS_MODULE_ID moduleId;

  /* Flag to indicate this object is in use  */
  bool inUse;

} DRV_PWM_OBJ;

// timer类型
// 高级 通用（L0） 通用（L1） 通用（L2） 基本
typedef enum {
  SENIOR_TIMER,
  L0_TIMER,
  L1_TIMER,
  L2_TIMER,
  PRIMARY_TIMER
} timer_type;

/* channel output parameter struct definitions */
typedef struct {
  uint16_t outputstate;  /*!< channel output state */
  uint16_t outputnstate; /*!< channel complementary output state */
  uint16_t ocpolarity;   /*!< channel output polarity */
  uint16_t ocnpolarity;  /*!< channel complementary output polarity */
  uint16_t ocidlestate;  /*!< idle state of channel output */
  uint16_t ocnidlestate; /*!< idle state of channel complementary output */
} timer_oc_para_t;

/* TIMER init parameter struct definitions*/
typedef struct {
  uint16_t prescaler;        /*!< prescaler value */
  uint16_t alignedmode;      /*!< aligned mode */
  uint16_t counterdirection; /*!< counter direction */
  uint16_t clockdivision;    /*!< clock division value */
  uint32_t period;           /*!< period value */
  uint8_t repetitioncounter; /*!< the counter repetition value */
} timer_para_t;

// PWM参数配置
typedef struct timer_pwm_cfg_tag {
  uint32_t timer_periph;
  timer_type timer_type;
  // uint16_t freq;

  uint16_t ocmode[16];
  uint16_t ocshadow[16];
  uint32_t duty[16];

  uint16_t ch_mask;
  timer_oc_para_t timer_ocintpara;
  timer_para_t timer_initpara;
} timer_pwm_cfg_t;

// PWM通道映射
// 比如PWM1映射到timer1 timer_ch_0
// PWM2映射到timer2 timer_ch_2
typedef struct timer_pwm_ch_mapping_tag {
  uint32_t timer_periph;
  uint8_t timer_ch;
} timer_pwm_ch_mapping_t;

void drv_pwm_cfg(const timer_pwm_cfg_t *pInit);

void drv_pwm_set_duty(uint8_t ch, uint16_t duty);

float drv_pwm_get_duty(uint8_t ch);

#endif /* _DRV_PWM_H_ */
